package com.cskt.exception;

import com.cskt.response.Result;
import com.cskt.response.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*@ControllerAdvice可以捕获所有控制层可能会出现的exception*/
@ControllerAdvice
public class ExceptionUtil {

    @ResponseBody
    @ExceptionHandler
    public Result exception(Exception e){
        return Result.error().message(e.getMessage());
    }

    //可以对异常类型进行细化
    @ResponseBody
    @ExceptionHandler
    public Result exception(IndexOutOfBoundsException e){
        return Result.error(ResultCode.INDEX_OUT_OF_BOUNDS_EXCEPTION);
    }

    @ResponseBody
    @ExceptionHandler
    public Result exception(ArithmeticException e){
        return Result.error(ResultCode.ARITHMETIC_EXCEPTION);
    }

    @ResponseBody
    @ExceptionHandler
    public Result exception(NullPointerException e){
        return Result.error(ResultCode.NULL_POINTER_EXCEPTION);
    }

    @ResponseBody
    @ExceptionHandler
    public Result exception(BusinessException e){
        return Result.error()
                .code(e.getCode()).message(e.getErrMsg());
    }
}
